﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using Database.Classes;

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
    public static SqlBoolean FleetExists(int systemId, int planetId)
    {
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT ColonyShips, Transports, Destroyers, Crusiers, Battleships FROM dbo.Planets Where PlanetID = @pid and SystemId = @sid", conn))
            {
                cmd.Parameters.Add("@sid", SqlDbType.Int).Value = systemId;
                cmd.Parameters.Add("@pid", SqlDbType.Int).Value = planetId;
                SqlDataReader rdr = cmd.ExecuteReader();
                rdr.Read();

                for (int i = 0; i < rdr.FieldCount; i++)
                {
                    if (int.Parse(rdr[i].ToString()) != 0)
                    {
                        conn.Close();
                        return SqlBoolean.True;
                    }
                }

            }
        }
        return SqlBoolean.False;
    }

    [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
    public static int FleetOwner(int systemId, int planetId)
    {
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT FleetOwnerID FROM dbo.Planets Where PlanetID = @pid and SystemId = @sid", conn))
            {
                cmd.Parameters.Add("@sid", SqlDbType.Int).Value = systemId;
                cmd.Parameters.Add("@pid", SqlDbType.Int).Value = planetId;
                SqlDataReader rdr = cmd.ExecuteReader();
                rdr.Read();
             //   conn.Close();
                return int.Parse(rdr[0].ToString());
            }
        }

    }
};

